import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  DatePicker,
  Select,
  Button,
  Space,
  Typography,
  Table,
  Tag,
  Progress,
} from 'antd';
import {
  ArrowUpOutlined,
  ArrowDownOutlined,
  DownloadOutlined,
  ReloadOutlined,
  UserAddOutlined,
  TeamOutlined,
  HeartOutlined,
  DollarOutlined,
} from '@ant-design/icons';
import { Line, Column, Pie, Area } from '@ant-design/charts';
import { formatDate } from '@/utils';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

interface OperationMetrics {
  userMetrics: {
    totalUsers: number;
    newUsersToday: number;
    activeUsers: number;
    userGrowthRate: number;
  };
  matchMetrics: {
    totalMatches: number;
    successfulMatches: number;
    matchSuccessRate: number;
    averageMatchScore: number;
  };
  revenueMetrics: {
    totalRevenue: number;
    vipUsers: number;
    conversionRate: number;
    arpu: number; // Average Revenue Per User
  };
  engagementMetrics: {
    avgSessionDuration: number;
    messagesSent: number;
    profileViews: number;
    dailyActiveRate: number;
  };
}

const OperationStats: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState<[string, string]>(['2024-01-01', '2024-01-31']);
  const [metrics, setMetrics] = useState<OperationMetrics | null>(null);

  // Mock metrics data
  const mockMetrics: OperationMetrics = {
    userMetrics: {
      totalUsers: 15628,
      newUsersToday: 142,
      activeUsers: 3456,
      userGrowthRate: 12.5,
    },
    matchMetrics: {
      totalMatches: 2847,
      successfulMatches: 1653,
      matchSuccessRate: 58.1,
      averageMatchScore: 82.3,
    },
    revenueMetrics: {
      totalRevenue: 485600,
      vipUsers: 2847,
      conversionRate: 18.2,
      arpu: 168.5,
    },
    engagementMetrics: {
      avgSessionDuration: 25.4,
      messagesSent: 18642,
      profileViews: 45821,
      dailyActiveRate: 22.1,
    },
  };

  // Mock chart data
  const userGrowthData = [
    { date: '2024-01-01', users: 12000, newUsers: 120 },
    { date: '2024-01-08', users: 12400, newUsers: 135 },
    { date: '2024-01-15', users: 13200, newUsers: 142 },
    { date: '2024-01-22', users: 14100, newUsers: 158 },
    { date: '2024-01-29', users: 15628, newUsers: 175 },
  ];

  const revenueData = [
    { month: '2023-09', revenue: 285000 },
    { month: '2023-10', revenue: 320000 },
    { month: '2023-11', revenue: 380000 },
    { month: '2023-12', revenue: 425000 },
    { month: '2024-01', revenue: 485600 },
  ];

  const channelData = [
    { channel: '抖音广告', users: 4250, cost: 85000, roi: 2.8 },
    { channel: '微信广告', users: 3680, cost: 72000, roi: 3.2 },
    { channel: '百度推广', users: 2140, cost: 48000, roi: 2.1 },
    { channel: '朋友推荐', users: 1850, cost: 0, roi: 0 },
    { channel: '其他渠道', users: 980, cost: 15000, roi: 1.5 },
  ];

  const userDistributionData = [
    { type: '免费用户', value: 82 },
    { type: 'VIP用户', value: 18 },
  ];

  const loadData = async () => {
    setLoading(true);
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000));
    setMetrics(mockMetrics);
    setLoading(false);
  };

  const handleExport = () => {
    // Export functionality
    console.log('Exporting data...');
  };

  const channelColumns = [
    {
      title: '推广渠道',
      dataIndex: 'channel',
      key: 'channel',
    },
    {
      title: '获客数量',
      dataIndex: 'users',
      key: 'users',
      render: (value: number) => value.toLocaleString(),
    },
    {
      title: '投入成本',
      dataIndex: 'cost',
      key: 'cost',
      render: (value: number) => value === 0 ? '-' : `¥${value.toLocaleString()}`,
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (value: number) => value === 0 ? '-' : `${value}x`,
    },
    {
      title: '效果评级',
      key: 'rating',
      render: (record: any) => {
        const { roi } = record;
        if (roi >= 3) return <Tag color="green">优秀</Tag>;
        if (roi >= 2) return <Tag color="orange">良好</Tag>;
        if (roi > 0) return <Tag color="red">待优化</Tag>;
        return <Tag color="blue">免费</Tag>;
      },
    },
  ];

  useEffect(() => {
    loadData();
  }, [dateRange]);

  if (!metrics) {
    return <div>Loading...</div>;
  }

  return (
    <div className="page-container">
      <div className="page-header">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Title level={4} className="page-title">运营数据</Title>
            <Text className="page-description">
              实时监控平台运营指标，支持自定义时间范围和数据导出
            </Text>
          </div>
          <Space>
            <RangePicker
              value={[dateRange[0], dateRange[1]] as any}
              onChange={(dates) => {
                if (dates) {
                  setDateRange([dates[0]!.format('YYYY-MM-DD'), dates[1]!.format('YYYY-MM-DD')]);
                }
              }}
            />
            <Button icon={<ReloadOutlined />} onClick={loadData} loading={loading}>
              刷新
            </Button>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>
              导出
            </Button>
          </Space>
        </div>
      </div>

      {/* Core Metrics */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={metrics.userMetrics.totalUsers}
              prefix={<TeamOutlined />}
              suffix={
                <div style={{ fontSize: '12px', color: '#52c41a' }}>
                  <ArrowUpOutlined /> {metrics.userMetrics.userGrowthRate}%
                </div>
              }
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="今日新增"
              value={metrics.userMetrics.newUsersToday}
              prefix={<UserAddOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="匹配成功率"
              value={metrics.matchMetrics.matchSuccessRate}
              precision={1}
              suffix="%"
              prefix={<HeartOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总收入"
              value={metrics.revenueMetrics.totalRevenue}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#eb2f96' }}
            />
          </Card>
        </Col>
      </Row>

      {/* Charts Row 1 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={12}>
          <Card title="用户增长趋势" loading={loading}>
            <Area
              data={userGrowthData}
              xField="date"
              yField="users"
              height={300}
              areaStyle={{ fill: '#1890ff', fillOpacity: 0.3 }}
              line={{ color: '#1890ff' }}
              point={{ size: 5, shape: 'diamond' }}
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="收入趋势" loading={loading}>
            <Column
              data={revenueData}
              xField="month"
              yField="revenue"
              color="#52c41a"
              height={300}
              columnWidthRatio={0.6}
            />
          </Card>
        </Col>
      </Row>

      {/* Detailed Metrics */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={16}>
          <Card title="推广渠道效果" loading={loading}>
            <Table
              dataSource={channelData}
              columns={channelColumns}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="用户构成" loading={loading}>
            <Pie
              data={userDistributionData}
              angleField="value"
              colorField="type"
              radius={0.8}
              height={250}
              label={{
                type: 'outer',
                content: '{name} {percentage}',
              }}
              interactions={[{ type: 'element-active' }]}
            />
          </Card>
        </Col>
      </Row>

      {/* KPI Cards */}
      <Row gutter={[24, 24]}>
        <Col xs={24} sm={12} lg={6}>
          <Card title="用户活跃度" loading={loading}>
            <div style={{ textAlign: 'center' }}>
              <Progress
                type="circle"
                percent={metrics.engagementMetrics.dailyActiveRate}
                format={percent => `${percent}%`}
                strokeColor="#1890ff"
                size={120}
              />
              <div style={{ marginTop: '12px' }}>
                <Text strong>日活跃率</Text>
                <br />
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  平均会话时长: {metrics.engagementMetrics.avgSessionDuration}分钟
                </Text>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card title="匹配质量" loading={loading}>
            <div style={{ textAlign: 'center' }}>
              <Progress
                type="circle"
                percent={metrics.matchMetrics.averageMatchScore}
                format={percent => `${percent}分`}
                strokeColor="#52c41a"
                size={120}
              />
              <div style={{ marginTop: '12px' }}>
                <Text strong>平均匹配分</Text>
                <br />
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  成功匹配: {metrics.matchMetrics.successfulMatches}对
                </Text>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card title="付费转化" loading={loading}>
            <div style={{ textAlign: 'center' }}>
              <Progress
                type="circle"
                percent={metrics.revenueMetrics.conversionRate}
                format={percent => `${percent}%`}
                strokeColor="#fa8c16"
                size={120}
              />
              <div style={{ marginTop: '12px' }}>
                <Text strong>VIP转化率</Text>
                <br />
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  ARPU: ¥{metrics.revenueMetrics.arpu}
                </Text>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card title="互动数据" loading={loading}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>消息发送</Text>
                <div style={{ fontSize: '24px', color: '#1890ff' }}>
                  {metrics.engagementMetrics.messagesSent.toLocaleString()}
                </div>
              </div>
              <div>
                <Text strong>资料浏览</Text>
                <div style={{ fontSize: '24px', color: '#52c41a' }}>
                  {metrics.engagementMetrics.profileViews.toLocaleString()}
                </div>
              </div>
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default OperationStats;